from django import forms
from web import models
from utils.bootstarpcss import BootStrapForm
from django.core.exceptions import ValidationError
from web.Forms.widgets import ColorRadioSelect


class project_form(BootStrapForm, forms.ModelForm):
    except_bootstrap_styles = ['color']

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea(),
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super(project_form, self).__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data.get('name')
        # 查询当前用户有没有创建该名称的项目
        exits = models.Project.objects.filter(creator=self.request.tracer.user, name=name)
        if exits:
            raise ValidationError('该项目名称已经创建过')
        # 查看当前用户额度是否足够
        # 当前项目的个数
        project_count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        # 购买的额度的个数
        if project_count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('可创建的额度已使用完，请购买')
        return name
